package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.heima.common.exception.CustException;
import com.heima.model.admin.dtos.AdUserDto;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.common.constants.AdminConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;
@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {
    @Override
    public ResponseResult login(AdUserDto dto) {
        /*1参数校验*/
        /*传入对象不为空、姓名不为空、密码不为空*/
        /*if (dto == null || StringUtils.isBlank(dto.getName()) || StringUtils.isBlank(dto.getPassword())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }*/
        /*2根据用户名查询用户信息，获取盐（盐是用来验证密码的）*/
        AdUser adUser = getOne(Wrappers.<AdUser>lambdaQuery()
                .eq(AdUser::getName, dto.getName())
                .eq(AdUser::getStatus, AdminConstants.ADUSER_NORMAL_STATUS));
        if (adUser == null) {
            CustException.cust(AppHttpCodeEnum.ADMIN_ADUSER_ISNOTEXIT_ERROR);
        }
        String salt = adUser.getSalt();     //盐
        String password = adUser.getPassword();
        /*按照相同的加密方式加密，比对密码*/
        String oripwd = DigestUtils.md5DigestAsHex((dto.getPassword()+salt).getBytes());
        if (!password.equals(oripwd)) {
            CustException.cust(AppHttpCodeEnum.ADMIN_ADUSER_NAMEORPWD_ERROR);
        }
        /*更新登陆时间*/
        adUser.setCreatedTime(new Date());
        updateById(adUser);
        /*生成TOKEN和用户信息返回给前端*/
        String token = AppJwtUtil.getToken(adUser.getId().longValue());
        HashMap<String, Object> resultMap = new HashMap<>();
        resultMap.put("token", token);
        adUser.setPassword(null);
        adUser.setSalt(null);
        resultMap.put("user", adUser);
        return ResponseResult.okResult(resultMap);
    }
}
